$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_xmch_m")
    let dgrid1 = $NG.getCmpApi("p_form_xmch_d1")
    const getHeadValue = (str) => mstform.getItem(str).getValue()

    isTabs()

    useValuesChange(() => {
        isTabs()
        if (page.oType == 'add') {
            getProjectChDetail()
        }
    }, "p_form_xmch_m.u_chzt")

    useValuesChange(() => {
        getProjectInfo()
    }, "p_form_xmch_m.u_xmmc")

    useUpdateRow(()=>{
        sumAmt()
    },"p_form_xmch_d1")

    function isTabs() {
        const bo = mstform.getItem("u_chzt").getValue()
        if (bo == '01') {
            selectTabs("tabPanel_tabItem")
        } else {
            selectTabs(1)
        }
        setTimeout(()=>{
            dgrid1 = $NG.getCmpApi("p_form_xmch_d1")
        },200)
    }

    // 标题编辑
    function sumAmt() {
        const rows = dgrid1.getRows()
        let yysr = 0 // %营业收入
        let gsglf = 0 // %公司管理费用
        let fjglf = 0 // %公司管理费用
        let cscbje = 0 // %成本测算费用
        // 汇总子明细到父节点
        childReduceTree(rows)
        rows.forEach(item => {
            switch (item.s_tree_name) {
                case '营业收入':
                    yysr += (Number(item.u_je) || 0)
                    break;
                case '成本测算':
                    cscbje += (Number(item.u_je) || 0)
                    break;
                case '公司':
                    gsglf += (Number(item.u_je) || 0)
                    break;
                case '分局':
                    fjglf += (Number(item.u_je) || 0)
                    break
            }
        })
        $NG.updateState((updater) => {
            updater.data.p_form_xmch_m.setProps({
                u_yysrbbyj: yysr,
                u_zcb: cscbje,
                u_gsglf: yysr !=0 ? (gsglf / yysr):0,
                u_fjglf: yysr !=0 ? (fjglf / yysr):0,
                u_lrl: yysr != 0 ? (yysr - cscbje) / yysr:0,
                u_sfks: (yysr !=0? ((yysr - cscbje) / yysr):0) <= 0 ? '01' : '02'
            })
        })
        dgrid1.refreshView()
    }

    // 汇总明细金额到父节点方法
    function childReduceTree(item) {
        if(Array.isArray(item)){
            item.forEach(el=>{
                if(!el.s_tree_pid || el.s_tree_pid.length < 3) {
                    el.u_je = childReduceTree(el)
                }
            })
            return item
        }
        let total_amt = 0
        if(item.children && item.children.length > 0) {
            item.children.forEach(el=>{
                el.u_je = childReduceTree(el)
                total_amt += childReduceTree(el)
            })
            return total_amt
        } else {
            return (Number(item.u_je) || 0)
        }
    }

    // 显示隐藏Tab页签
    function selectTabs(key) {
        const tabs = $NG
            .getCompMap()
            .get("__Tabs__")[0]
            .getApi();

        tabs.updateItems((innerItems, activeKey) => {
            return [...innerItems.filter((item) => {
                if (item.name == key) {
                    return item
                }
            })];
        });

        tabs.setActiveKey(key);
    }

    // 获取项目信息
    function getProjectInfo() {
        const phid = mstform.getItem("u_xmmc").getValue()
        if (!phid) return
        $NG.execServer("getProjectInfoByPhid", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_xmch_m.setProps({
                    u_htqdrq: datas.user_htqdrj,
                    u_zbrq: datas.user_zbrq,
                    u_htje: datas.approx_contract_fc,
                    u_htrq: datas.limit_time
                })
            })

        })
    }
    // 获取基础表信息
    function getProjectChDetail() {
        $NG.execServer("getProjectChDetail", {}, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                value.push(item.extendObjects)
                return value
            }, [])
            setTimeout(() => {
                const dgrid1 = $NG.getCmpApi("p_form_xmch_d1")
                const arr = arrayToTree(datas, "s_tree_id", "s_tree_pid")
                console.log(`添加的数据`, arr, datas);
                $NG.updateState((updater) => {
                    updater.data.p_form_xmch_d1.setProps(p => {
                        return arr
                    })
                })
                $NG.updateUI(updater => updater.grid.p_form_xmch_d1.s_tree_no.setProps(p => { return { ...p, levelSumary: true } }));
            }, 200)
        })
    }

    // 转属性结构
    function arrayToTree(items, idField = "id", parentField = "parentId", childrenField = "children") {
        const map = {};
        const roots = [];

        // 先建立 id → item 的映射
        items.forEach(item => {
            map[item[idField]] = { ...item, [childrenField]: [] };
        });

        // 组装树
        items.forEach(item => {
            const parentId = item[parentField];
            if (parentId == null || parentId.length < 2 || parentField == '0') {
                // 根节点
                roots.push(map[item[idField]]);
            } else if (map[parentId]) {
                // 挂到父节点的 children 上
                map[parentId][childrenField].push(map[item[idField]]);
            }
        });

        return roots;
    }
})